﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Configuration;
using System.IO;
using System.Text;

/// <summary>
/// Summary description for TemplateManager
/// </summary>
public class TemplateManager
{
    private const int QUESTION_NO = 15;
    private string templatePath;
    private string content;
    private ReportBuilder reportBuilder;
    private string url;
    private string reportContent;
    private string serverPath;
    private string fileName;
    #region Publie Properties
    public string ReportContent {
        get { return this.reportContent; }
    }
    #endregion

    public TemplateManager(ReportBuilder reportBuilder, string fileName)
	{
        this.fileName = fileName + ".html";
        serverPath = HttpContext.Current.Server.MapPath(".");
        this.reportBuilder = reportBuilder;
        url = ConfigurationManager.AppSettings["url"].ToString();
        templatePath = Path.Combine(HttpContext.Current.Server.MapPath("."), ConfigurationManager.AppSettings["template"].ToString());
        loadTemplate();
        List<Question> qs = reportBuilder.Importance;
        replaceTokens(qs.ConvertAll(new Converter<Question, ReportEntry>(reToReportEntry)), "$Importance$");
        qs = reportBuilder.Presured;
        replaceTokens(qs.ConvertAll(new Converter<Question, ReportEntry>(reToReportEntry)), "$Presured$");
        List<Conflict> cs = reportBuilder.Conflict;
        replaceTokens(cs.ConvertAll(new Converter<Conflict, ReportEntry>(coToReportEntry)), "$Conflicted$");
        List<UnderAchieved> ua = reportBuilder.UnderAchived;
        replaceTokens(ua.ConvertAll(new Converter<UnderAchieved, ReportEntry>(uaToReportEntry)), "$UnderAchieved$");

        fillScore("$ImportanceScore$", reportBuilder.ImportanceScore);
        fillScore("$PresureScore$", reportBuilder.PressureScore);
        fillScore("$ActivityScore$", reportBuilder.ActivityScore);
        fillScore("$SuccessScore$", reportBuilder.SuccessScore);
        fillScore("$AoidanceImportanceScore$", reportBuilder.Imptc_avdc);
        fillScore("$AoidancePresureScore$", reportBuilder.Pres_avdc);
        fillScore("$AoidanceActivityScore$", reportBuilder.Aty_avdc);
        fillScore("$AoidanceSuccessScore$", reportBuilder.Sces_avdc);                                                                                             
	}

    private ReportEntry uaToReportEntry(UnderAchieved underAchived)
    {
        ReportEntry retVal = new ReportEntry();
        retVal.No = underAchived.Number;
        retVal.Description = underAchived.QuestionDescription;
        return retVal;
    }

    private ReportEntry coToReportEntry(Conflict conflict)
    {
        ReportEntry retVal = new ReportEntry();
        retVal.Description = conflict.QuestionDescription;
        retVal.No = conflict.Number;
        return retVal;
    }

    private ReportEntry reToReportEntry(Question q)
    {
        ReportEntry retVal = new ReportEntry();
        retVal.No = q.No;
        retVal.Description = q.Description;
        return retVal;
    }

    private void loadTemplate()
    {
        StreamReader sr = new StreamReader(templatePath);
        content = sr.ReadToEnd().Trim();
        reportContent = content;
        sr.Close();
        sr.Dispose();
    }

    private void fillScore(string token, double score)
    {
        string strScore = score.ToString("F3");
        reportContent = reportContent.Replace(token, strScore);
    }

    // $Importance1$
    private void replaceTokens(List<ReportEntry> entries, string token)
    {
        string[] t = token.Split('$');
        string[] tokens = new string[QUESTION_NO];
        for(int i = 0;i < QUESTION_NO;i++)
        {
            tokens[i] = "$" + t[0] + t[1] + (i+1) + "$";
        }
        
        for(int i = 0;i < QUESTION_NO;i++)
        {
            reportContent = reportContent.Replace(tokens[i], entries[i].No + "." + entries[i].Description);
        }
    }

    public void Download()
    {
        FileInfo fileInfo = null;
        if (this.fileName.Equals("")){
            fileInfo = new FileInfo(Path.GetTempFileName());
            this.fileName = fileInfo.Name.Split('.')[0] + ".html";
        }                    
        FileStream fs = File.Create(Path.Combine(Path.Combine(serverPath, "tmp"), this.fileName));

        UnicodeEncoding uniEncoding = new UnicodeEncoding();
        fs.Write(uniEncoding.GetBytes(this.reportContent), 0, uniEncoding.GetByteCount(this.reportContent));
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("Content-Length", fs.Length.ToString());
        HttpContext.Current.Response.ContentType = "application/octet-stream";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + "report.htm");
        fs.Close();
        fs.Dispose();
        HttpContext.Current.Response.TransmitFile(fs.Name);
    }
}
